package com.xy.auth;

import com.alibaba.fastjson2.JSONObject;
import com.xy.api.constant.RedisConstant;
import com.xy.api.exception.AuthorizationException;
import com.xy.api.model.dto.system.UserInfoDTO;
import com.xy.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Objects;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${login.sessionTime:60}")
    private Integer sessionTime;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("Authorization");
//        if (!StringUtils.hasText(token)) {
//            throw new AuthorizationException("用户未登录");
//        }
//        String key = String.format(RedisConstant.TOKEN, token);
//        String userInfoStr = redisUtil.get(key);
//        if (!StringUtils.hasText(userInfoStr)) {
//            throw new AuthorizationException("用户未登录");
//        }
//        UserInfoDTO userInfo = JSONObject.parseObject(userInfoStr, UserInfoDTO.class);
//        if (Objects.isNull(userInfo)) {
//            throw new AuthorizationException("用户未登录");
//        }
//        redisUtil.expire(token, Duration.ofMinutes(sessionTime));
//        UserContext.put(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        UserContext.clear();
    }
}
